package com.jash.encryption;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;


/**
 * A simple {@link Fragment} subclass.
 */
public class RSAFragment extends Fragment implements View.OnClickListener {
    private static final String PUB_STR = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPWQMT9Iv4qShOv1DBLwwnFf03LYVgfInzNV7x" +
            "VqPzrXix14tgyi6Cx8IaOXNcFYRrDPkJ+HDd6Is8MvB7S6kVdw7emY30lsQr0HIl8RlSzrjRApcU" +
            "0p9zXzM2ssNrM2KI8poleXyVaEPItailrvP41J54ddrqPn7+RldUG/Qy/QIDAQAB";
    private static final String PRI_STR = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAM9ZAxP0i/ipKE6/UMEvDCcV/Tct\n" +
            "hWB8ifM1XvFWo/OteLHXi2DKLoLHwho5c1wVhGsM+Qn4cN3oizwy8HtLqRV3Dt6ZjfSWxCvQciXx" +
            "GVLOuNEClxTSn3NfMzayw2szYojymiV5fJVoQ8i1qKWu8/jUnnh12uo+fv5GV1Qb9DL9AgMBAAEC" +
            "gYA4MIcFAWBtImop7O6Va4p/jRXxvgRHAXjgz7XK8Q+9GWV7zE2ZDTFNf5S6RpdcfPhFil5ytUDg" +
            "4gPZbHR+9SH8kkeWd7b8QwaeCgfn5KFDG44lKB2OneuHByVo2OBFTaxJrPwqVwjIrn5WTPwBiaom" +
            "8QrxzkIYOYth5VaIiBPOgQJBAOecFle2CeSw4Ia5T5rfiDSf6PmJ9wMEm527cAeZsPub6S7pwGIo" +
            "J77kh4FDNo0CfwpEf3E/tfRN62UfvhmA03cCQQDlLtnLkQ5Mjm981hmAEYzWvC6/q+yFbRtKvpRq" +
            "dHpc4mypUB3Ht5qHmU308IaTPrpvr7nsVXXaDZ9Sy+mElEIrAkEAp3z/x0QUWXXzmFmwEH5vwCaX" +
            "0sULhPozEti2RjjFfN6dvVg60IDbZTdcKoURkN1qQ2GPi7UX/ujOPp262jSINwJAMbhqU7mSipVU" +
            "JpckTR6BmYyV78tSsteq1hpmhHnkmgYdYNYav9tbURO3T+5mo8c2F0jeYyFfQgE2kXXfoX2wpQJB" +
            "AMdtumn/j6AaWjUeSpbVBFm54EQ6x2d0l7W0MLbhwtT6INsIq1RllhFijbuAbhka9kp16htJlQTB" +
            "kdf3EnJfjG4=";
    private PublicKey publicKey;
    private PrivateKey privateKey;
    private TextInputLayout src;
    private TextInputLayout rlt;

    public RSAFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_rsa, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        try {
            KeyFactory factory = KeyFactory.getInstance("rsa");
            X509EncodedKeySpec x509 = new X509EncodedKeySpec(Base64.decode(PUB_STR, Base64.NO_WRAP));
            publicKey = factory.generatePublic(x509);
            PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(Base64.decode(PRI_STR, Base64.NO_WRAP));
            privateKey = factory.generatePrivate(pkcs8);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        src = ((TextInputLayout) view.findViewById(R.id.rsa_src));
        rlt = ((TextInputLayout) view.findViewById(R.id.rsa_rlt));
        view.findViewById(R.id.ras_encryption).setOnClickListener(this);
        view.findViewById(R.id.ras_decryption).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            switch (view.getId()) {
                case R.id.ras_encryption:
                    String src_str = src.getEditText().getText().toString();
                    if (TextUtils.isEmpty(src_str)) {
                        src.setError("不能为空");
                        src.setErrorEnabled(true);
                    } else {
                        src.setErrorEnabled(false);
                        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
                        byte[] bytes = cipher.doFinal(src_str.getBytes());
                        rlt.getEditText().setText(Base64.encodeToString(bytes, Base64.NO_WRAP));
                    }
                    break;
                case R.id.ras_decryption:
                    String rlt_str = rlt.getEditText().getText().toString();
                    if (TextUtils.isEmpty(rlt_str)) {
                        rlt.setError("不能为空");
                        rlt.setErrorEnabled(true);
                    } else {
                        rlt.setErrorEnabled(false);
                        cipher.init(Cipher.DECRYPT_MODE, publicKey);
                        byte[] bytes = cipher.doFinal(Base64.decode(rlt_str, Base64.NO_WRAP));
                        src.getEditText().setText(new String(bytes));
                    }
                    break;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
    }
}
